
import fs from 'fs';
import {speech, HttpClient} from 'baidu-aip-sdk';

import {exesql} from '../database/db';
import {sendLogToEmail} from './logger';
import { playBaiduAudio } from './baidu_api';

const NOT_FOUND_URL = 'http://story.aidoor.net/not_found.mp3';
const CARD_URL = 'http://story.aidoor.net/card_mp3/';

/**
 * 读卡模式
 */
class ReadCard {
	constructor() {
        this.initSpeech();
        this.getCardUrl = this.getCardUrl.bind(this);
    }

    initSpeech(){
        const APP_ID = "11224737";
        const API_KEY = "h7tI4EVt93mvMTFMDtV9AM6Q";
        const SECRET_KEY = "RoG63sftVIGpCwngj8SDfKcyUKzgcy6u";

        this.client = new speech(APP_ID, API_KEY, SECRET_KEY);
        HttpClient.setRequestInterceptor(function(requestOptions) {
            // 查看参数
            console.log(requestOptions)
            // 修改参数
            requestOptions.timeout = 5000;
            // 返回参数
            return requestOptions;
        });
    }
    

	async getCardUrl(req, res) {
		const card_id = req.query.card_id;
		const uuid = req.query.uuid;
        const sql = 'select * from card_read where card_id=?';
        let post = {
            errcode:0,
            errmsg:'ok',
            data:''
        };
        try {
            const {err ,result} = await exesql(sql, [card_id]);
            if (err) {
                res.end(JSON.stringify(post));
                sendLogToEmail(err);
                return;
            }
            if (result.length === 0) {
                Object.assign(post, {data:NOT_FOUND_URL});
                res.end(JSON.stringify(post));
                return;
            }

            const first = result[0];
            // 如果节目id存在,
            if (first.track_id !== 0) {
                this.play(first.album_id, first.track_id, uuid);
                res.end(JSON.stringify(post));
                return;
            }

            // 没有对应的URL
            if (first.url === '') {
                this.getText2audio(first,uuid).then(result => {
                    if (!result) {
                        res.end(JSON.stringify(post));
                        return;
                    }
                    const fileName = this.getFileName(first);
                    fs.writeFileSync(fileName, result.data);
                    const sql = 'update card_read set url =? where id=?';
                    const url = this.getFileUrl(card);
                    exesql(sql, [url, card.id]).then(function (data) {
                        if(data.err) {
                            sendLogToEmail(data.err);
                            res.end(JSON.stringify(post));
                        }else {
                            Object.assign(post,{data:url});
                            res.end(JSON.stringify(post));
                        }
                    })
                },err => {
                    res.end(JSON.stringify(post));
                });
                return;
            }

            if (first.type == 2){
                console.log('本地数据 url=', first.url);
                Object.assign(post,{data:first.url});
                res.end(JSON.stringify(post));
                return 
            }

            // 检查文件是否存在
            const fileName = this.getFileName(first);
            const exists = await this.existsFile(fileName);
            if(exists){
                Object.assign(post,{data:first.url});
                res.end(JSON.stringify(post));
            }else{
                this.getText2audio(first,uuid).then(result => {
                    if (!result) {
                        res.end(JSON.stringify(post));
                        return;
                    }
                    fs.writeFileSync(fileName, result.data);
                    const sql = 'update card_read set url =? where id=?';
                    const url = this.getFileUrl(card);
                    exesql(sql, [url, card.id]).then(function (data) {
                        if(data.err) {
                            sendLogToEmail(data.err);
                            res.end(JSON.stringify(post));
                        }else {
                            Object.assign(post,{data:url});
                            res.end(JSON.stringify(post));
                        }
                    })
                },err => {
                    res.end(JSON.stringify(post));
                });
            }

        } catch (err) {
            sendLogToEmail(err);
            res.end(JSON.stringify(post));
        }
    }



    // 检查文件是否存在 
    existsFile(fileName){
        return new Promise(function(resolve, reject) {
            fs.exists(fileName, function(exists){
                resolve(exists);
            })
        })
    }

    // 调用百度SDK接口
    getText2audio(card,uuid){
        const para = {
            spd:card.spd,
            pit:card.pit,
            vol:card.vol,
            per:card.per
        };
        return this.client.text2audio(card.tex, para);
    }


    /**
     * 调用百度接口播放音频
     * @param {*} album_id 
     * @param {*} track_id 
     * @param {*} uuid 
     */
    async play(album_id, track_id, uuid){
        const sql = 'select * from device where uuid=?';
        try {
            const {err ,result} = await exesql(sql,[uuid]);
            if (err) {
                sendLogToEmail(err);
                return;
            }
            if (result.length > 0) {
                playBaiduAudio(uuid,album_id,track_id,result[0].token);
            }
        } catch (err) {
            sendLogToEmail(err);
        }
    }

    getFileName(card){
        return './web/card_mp3/' + card.id + '.mp3';
    }

    getFileUrl(card){
        return CARD_URL + card.id + '.mp3';
    }

}

export default new ReadCard();
